package de.blitzcoder.collide;

// Imports
import de.blitzcoder.collide.engine.RunningProcess;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import de.blitzcoder.collide.util.Log;
import de.blitzcoder.collide.gui.CodeDocument;
import de.blitzcoder.collide.gui.Document;
import de.blitzcoder.collide.gui.textarea.CollIDETextArea;
import de.blitzcoder.collide.templatemanager.Template;


/*
BlitzMax IDE
 **************************************************
Copyright (c) 2007-2008 by Johannes Wotzka
All Rights reserved
--------------------------------------------------
File: ide/End.java

End.exitIDE() is called on end to close and save open codes etc.
 */
public class End {

    /**
     * END FUNCTION
     */
    public static void exitIDE() {

        Log.log("Exitting");

        // Save recent open files
        saveRecent();

        // Save persistent layout
        Interface.get().savePersistentLayout();

        // If cancel was clicked while code Saving, false is returned and the end is canceld
        if (!Interface.getDocumentManager().removeAllDocuments()) {
            return;
        }

        // Save Configuration
        Config.save();

        // Kill running Processes
        killRunningProcesses();

        // Save highlighter settings
        CollIDETextArea.getPropertyManager().save();

        // Save Templates
        Template.saveTemplates();

        Log.end();
        System.exit(0);
    }

    public static void killRunningProcesses() {
        
        Document[] docs = Interface.getOutput().getAllDocuments();
        for (Document d:docs) {
            if (d instanceof RunningProcess) {
                RunningProcess p = (RunningProcess)d;
                p.killProcess();
            }
        }
        
    }

    public static void saveRecent() {

        Log.log("Saving session");

        File file = new File("recentFiles.dat");

        if (file.exists()) {
            file.delete();
        }

        try {
            file.createNewFile();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {

            BufferedWriter w = new BufferedWriter(new FileWriter(file));

            Document[] docs = Interface.getDocumentManager().getAllDocuments();
            for(Document doc:docs) {

                if (doc instanceof CodeDocument) {

                    CodeDocument codeDoc = (CodeDocument)doc;

                    
                    if (Interface.get().toolBar.actionSelectBuildFile.getSelectedIndex() != 0 && CodeDocument.getCompileCode() == codeDoc) {
                        w.write("[build]");
                    }

                    w.write(codeDoc.getFile().getAbsolutePath() + "\n");
                }

            }

            w.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
